package com.javazyw.utils.io;

import org.apache.commons.lang.StringUtils;

public class ByteUtils {
	
	//将整形拆分四个字节
	public static byte[] intToByteArray(int i) {   
		  byte[] result = new byte[4];   
		  result[0] = (byte)((i >> 24) & 0xFF);
		  result[1] = (byte)((i >> 16) & 0xFF);
		  result[2] = (byte)((i >> 8) & 0xFF); 
		  result[3] = (byte)(i & 0xFF);
		  return result;
   }
    // 二进制字节转16进制
	public static String binaryToHexString(byte[] bytes){
		String hexStr =  "0123456789ABCDEF";
		String result = "";
		String hex = "";
		for(int i=0;i<bytes.length;i++){
			//字节高4位
			hex = String.valueOf(hexStr.charAt((bytes[i]&0xF0)>>4));
			//字节低4位
			hex += String.valueOf(hexStr.charAt(bytes[i]&0x0F));
			result +=hex+" ";
		}
		return result;
	}
	
	/**
	 * 创建带有长度的字节数组.
	 * @param message
	 * @return
	 */
	public static byte[] buildBytesWithLength(String message) {
		
		if (StringUtils.isEmpty(message)) {
			return null;
		}
		
		byte[] by = message.getBytes();
    	int len = by.length;
		byte[] lenByte = ByteUtils.intToByteArray(len);
		byte[] n = new byte[by.length+lenByte.length];
		System.arraycopy(lenByte, 0, n,0,lenByte.length);
		System.arraycopy(by, 0, n,lenByte.length,by.length);
		
		return n;
	}
}
